package cc.jt.apt.processor;

import cc.jt.apt.annotation.Entity;
import cc.jt.apt.annotation.orm.Table;
import cc.jt.apt.annotation.Entity;
import cc.jt.apt.annotation.orm.Table;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;

public class APTProcessor extends AbstractProcessor {

  @Override
  public Set<String> getSupportedAnnotationTypes() {
    Set<String> supportedAnnotationTypes = new HashSet<>();
    supportedAnnotationTypes.add(Entity.class.getCanonicalName());
    supportedAnnotationTypes.add(Table.class.getCanonicalName());
    return supportedAnnotationTypes;
  }

  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    System.out.println("APT run start..." + roundEnv.toString());

    for (TypeElement annotation : annotations) {
      for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
        if (element instanceof TypeElement) {
          TypeElement typeElement = (TypeElement) element;
          System.out.println("APT run start typeElement..." + typeElement);

          String className = typeElement.getSimpleName().toString() + "Generated";
          String packageName = processingEnv.getElementUtils().getPackageOf(typeElement).toString();
          String content = generateGeneratedClassContent(packageName, className);

          try {
            // 创建一个新的Java源文件
            Writer writer = processingEnv.getFiler().createSourceFile(packageName + "." + className, typeElement).openWriter();
            writer.write(content);
            writer.flush();
            writer.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
    return true;
  }

  @Override
  public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latestSupported();
  }

  private String generateGeneratedClassContent(String packageName, String className) {
    return "package " + packageName + ";\n\n"
        + "public class " + className + " {\n\n"
        + "    public static void printMessage() {\n"
        + "        System.out.println(\"Hello from " + className + "!\");\n"
        + "    }\n\n"
        + "}\n";
  }

}
